package cn.sccdlg.ssm.controller;

import cn.sccdlg.ssm.domain.Product;
import cn.sccdlg.ssm.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/27 22:47
 * 商品Controller
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    /** 错误页面*/
    private static final String ERROR_PAGE = "error";

    /**
     * 查询全部产品
     */
    @RequestMapping("/findAll.do")
    @RolesAllowed("ADMIN")
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView();
        try {
            List<Product> ps = productService.findAll();
            mv.addObject("productList", ps);
            mv.setViewName("product-list1");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询所有商品失败！", e);
            mv.setViewName(ERROR_PAGE);
        }
        return mv;
    }

    /**
     * 添加商品
     * @param product 商品信息
     */
    @RequestMapping("/save.do")
    public String save(Product product) {
        try {
            productService.save(product);
            return "redirect:findAll.do";
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("添加商品失败！", e);
        }
        return ERROR_PAGE;
    }

    /**
     * 查询单个商品信息详情
     * @param id 商品id
     */
    @RequestMapping("/info.do")
    public ModelAndView info(String id) {
        ModelAndView mv = new ModelAndView();
        try {
            Product product = productService.findById(id);
            mv.addObject("product", product);
            mv.setViewName("product-update");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询商品失败！", e);
            mv.setViewName(ERROR_PAGE);
        }
        return mv;
    }

    /**
     * 修改商品信息
     * @param product 商品信息
     */
    @RequestMapping("/update.do")
    public String update(Product product) {
        try {
            productService.update(product);
            return "redirect:findAll.do";
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("修改商品失败！", e);
        }
        return ERROR_PAGE;
    }
}
